package com.qing.provider.controller;

import com.qing.api.pojo.User;
import com.qing.provider.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

// 提供RestFul 服务
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //获取一些配置信息，得到具体的微服务！
    @Autowired
    private DiscoveryClient client;

    //注册进来的微服务，获取一些消息
    @GetMapping("/client")
    public Object discovery(){
        //获取微服务列表的清单
        List<String> list=client.getServices();
        System.out.println("discovery==>services:"+list);

        //获取一个具体服务信息，通过 具体的微服务ID
        List<ServiceInstance> serviceInstances=client.getInstances(" springcloud-provider-user");
        serviceInstances.forEach((item)->{
            System.out.println(item.getHost()+"\t"+item.getUri()+"\t"+item.getMetadata()+"\t"+item.getPort()+"\t"+item.getScheme()+"\t"+item.getServiceId());
        });
        return this.client;
    }


    @PostMapping
    public void insert(@RequestBody User user){
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setDbSource("testdb1");
        userService.addUse(user);
    }

    @GetMapping("/{id}")
    public User findById(@PathVariable("id") Long id){
        return  userService.queryById(id);
    }


    @GetMapping("/all")
    public List<User> findByName(@RequestParam(value = "name",defaultValue = "",required = false) String name){
        return  userService.queryUser(name);
    }

    @DeleteMapping
    public void delete(@RequestParam(value = "id") Long id){
        userService.deleteById(id);
    }

}
